package com.mezz.bones.im.gateway.action.interfaces;


import cn.hutool.core.bean.BeanUtil;
import com.mezz.bones.im.common.exception.ImBaseException;
import com.mezz.bones.im.common.result.ImResultCode;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Set;

public abstract class AbstractSysMessageAction<Req> implements SysMessageAction<Req> {

  @Resource
  private Validator validator;

  @Override
  public void checkParam(Req req) {
    // 手动验证
    Set<ConstraintViolation<Req>> violations = validator.validate(req);

    if (!violations.isEmpty()) {
      // 获取第一个错误并抛出异常
      ConstraintViolation<Req> violation = violations.iterator().next();
      log.error("Validation error: {}", violation.getMessage());
      throw new ImBaseException(ImResultCode.PARAM_ERROR, "参数验证失败: " + violation.getMessage());
    }
  }

  @Override
  public Req convert2T(Object body) {

    // Get the actual type argument from the generic class
    ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
    Type actualTypeArgument = parameterizedType.getActualTypeArguments()[0]; // Get the generic type (e.g., List<String>)

    // Parse the object to the specific type
    Object res = BeanUtil.toBean(body, ((Class) actualTypeArgument));
    return (Req) res;
  }
}
